<template>
    <ElDialog v-model="dialogVisible" width="600px" :title="title">
        <UiForm :formData="formData" @close="dialogVisible = false" @callback="submitForm"/>
    </ElDialog>
</template>
<script setup>
import {ElDialog, ElMessage } from 'element-plus'
import UiForm from '@/components/uiForm.vue'
import { computed, ref, reactive, onMounted } from 'vue';
import {channelStatus} from "@/utils/enum.js"
import {cascaderAddress} from '@/utils/addressData';
import {setChannel} from "@/server/manage/channel.js"
import { isMobile } from '@/utils/validate'

const props = defineProps(['modelValue', 'type', 'info'])
const emit = defineEmits(['update:modelValue', "callback"])
// 手机号验证
const validateMobile = (rule, value, callback) => {
    if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
    } else {
        callback()
    }
}
const formData = reactive([
    {label: "渠道名称", type: 'input',key: "channelName", value: '', required: true},
    {label: "地区", type: 'cascader', key: "areaCode", value: '', required: true, cascaderOptions: cascaderAddress()},
    {label: "合作时间", type: 'datePicker', key: "cooperateTime", widgetType: 'daterange', value: '', required: true},
    {label: "联系人", type: 'input',key: "contacts", value: '', required: true},
    {label: "联系电话", type: 'input',key: "contactTel", value: '', required: true, rules: { validator: validateMobile, trigger: 'blur' }},
    {label: "状态", type: 'radio', key: "dataStatus", value: '1', required: true, options: channelStatus}, 
    {label: "备注", type: 'input', key: "remark", widgetType: "textarea", value: '', required: false},
])
const dialogVisible = computed({
    set:(val) => {
        emit('update:modelValue', val)
    },
    get:() => {
        return props.modelValue
    }
})
const title = computed(() => {
    let obj = {add: '新增',edit: '编辑' }
    return obj[props.type]
})
// 提交
const submitForm = (formData) => {
    let obj = {add: 'save',edit: 'update' }
    let params = formData
    if(Array.isArray(params.areaCode)) {params.areaCode = params.areaCode.join('/')}
    params.cooperateStartTime = params.cooperateTime[0]
    params.cooperateEndTime = params.cooperateTime[1]
    if(props.info?.id) {
        params.id = props.info.id
        for(let key in props.info){
            if(!params[key]) params[key] = props.info[key]
        }
    }
    setChannel(params, obj[props.type]).then(res => {
        dialogVisible.value = false
        emit('callback')
        ElMessage({ message: "操作成功！", type: 'success'})
    })
}
// 获取详情
const getDetail = () => {
    formData.forEach((item) => {
        item.value = props.info[item.key]
        if(item.key === "areaCode") {item.value = item.value?.split('/')}
        if(item.key === "cooperateTime") {item.value = [props.info.cooperateStartTime, props.info.cooperateEndTime]}
    })
}
onMounted(() => {
    if(props.type === 'edit') {getDetail()}
})
</script>